<?php
require_once 'BaseController.php';

/**
 * 【PC版】まとめて問い合わせ コントローラ
 */
class Renew_Bukkenentry2Controller extends Renew_BaseController
{

    /**
     * メインアクション(post)
     */
    public function postAction()
    {
        $params = $this->getParameters();
        $step = $params['Step'];

        $this->makeTemplateParams($params);
        $this->_data['params'] = $params;

        if (empty($step))
        {
            $this->displayBody2('index');
        }
        else
        {
            $p_campaigns = $this->collectCampaignFromParams($params);
            $this->_data['p_campaigns'] = $p_campaigns;

            $model_cam = new Renew_Model_BukkenCampaign();
            $temp = $model_cam->getNormalCampaigns(); // キャンペーンデータ取得

            $this->makeTemplateParams1($params);

            if ($step == 1)
            {
                $this->_data['CAMPAIGNS'] = $temp;
                $this->displayBody2('entry');
            }
            else if ($step == 2)
            {
                if ($this->checkParams($params))
                {
                    // 入力にエラーがある場合
                    $campaigns = array();
                    foreach ($temp as $k => $cam)
                    {
                        if (in_array($cam['M94_CAMPAIGN_CD'], $p_campaigns))
                        {
                            $cam['name'] = 'campaign' . $k;
                            $cam['checked'] = 1;
                        }
                        $campaigns[] = $cam;
                    }
                    $this->_data['CAMPAIGNS'] = $campaigns;
                    // エラー画面へ遷移
                    $this->displayBody2('error');
                }
                else
                {
                    // 入力にエラーがない場合
                    $campaigns = array();
                    foreach ($temp as $k => $cam)
                    {
                        if (in_array($cam['M94_CAMPAIGN_CD'], $p_campaigns))
                        {
                            $cam['name'] = 'campaign' . $k;
                            $campaigns[] = $cam;
                        }
                    }
                    $this->_data['CAMPAIGNS'] = $campaigns;
                    // 確認画面へ遷移
                    $this->displayBody2('confirm');
                }
            }
            else if ($step == 3)
            {
                $cparams = array();
                $cparams['Tel'] = $params['Tel'];
                $cparams['Mail'] = $params['Mail'];
                $cparams['vintGenruFlg'] = 0;
                $cparams['NameSei'] = $params['KanjiSei'];
                $cparams['NameMei'] = $params['KanjiMei'];
                // 20141211 S_Add
                $cparams['NameSeiKana'] = $params['KanaSei'];
                $cparams['NameMeiKana'] = $params['KanaMei'];
                // 20141211 E_Add

                $list = $this->extractParams($params, 'BukkenCd');
                $cparams['BukkenCd'] = join(',', $list);

                $list = $this->extractParams($params, 'check');
                if (array_key_exists('check1', $params)) $cparams['Inquiry1'] = 1;
                if (array_key_exists('check2', $params)) $cparams['Inquiry3'] = 1;
                if (array_key_exists('check3', $params)) $cparams['Inquiry2'] = 1;
                if (array_key_exists('check4', $params)) $cparams['Inquiry4'] = 1;

                $list = $this->extractParams($params, 'campaign');
                $cparams['Comment'] = $params['shosai'];

                $list = $this->extractParams($params, 'campaign');
                $cparams['CampaignAgechau'] = join(';', $list);
                $cparams['TimeStr'] = date("Y/m/d H:i:s");

                $this->callInquiryApi('apibukken', $cparams);
                $code = $this->extractParams($params, 'BukkenCd');
                $code = join('&BukkenCds[]=', $code);

                $this->my_secure_redirect("inquiry/bukkenentry/-/complete/?requestID={$this->_CV_data['CV_ToiawaseId']}&BukkenCds[]={$code}&revenue={$this->_CV_data['CV_TotalAmounts']}&ShopCds[]=" . join('&ShopCds[]=', $params['scds']));
            }
        }
    }

    /**
     * テンプレート用パラメータ作成
     *
     * @param unknown $params リクエストパラメータ
     */
    private function makeTemplateParams($params)
    {
        $dbParams = array();

        $c = 0;
        $bukkenCds = "";
        foreach ($params as $key => $val)
        {
            if (substr($key, 0, 8) == 'BukkenCd')
            {
                $key = ":BukkenCd_" . $c;
                if ($c > 0) $bukkenCds .= " , ";
                $bukkenCds .= $key;
                $dbParams[$key] = $val;
                $c++;
            }
        }

        $items = array();

        $model = new Renew_Model_BukkenList2();
        $model_conv = new Rstobi_Model_Converte();

        $isMobile = false;
        $doChunk = true;
        $chunkLength = -1;
        $data = $model->getBukkenList($bukkenCds, $dbParams);
        $model_conv->dataConverteForBuken($data, $params, $isMobile, $doChunk, $chunkLength);

        $model_cam = new Renew_Model_BukkenCampaign();
        $norm_cam = $model_cam->getNormalCampaigns();

        $prev = NULL;
        $c = -1;
        foreach ($data[0] as $d)
        {
            $tatemono = $d['T03_DAIHYO_TATEMONO_CD'];
            if ($prev != $tatemono)
            {
                $c++;
                $items[] = array();
            }
            $d['MAX_CHINRYO_STR'] = (intval($d['MAX_CHINRYO']) / 10000);
            $d['MIN_CHINRYO_STR'] = (intval($d['MIN_CHINRYO']) / 10000);
            $heya_cam = $model_cam->getHeyaCampaigns($d['T03_HEYA_CD']);
            $d['CAMPAIGNS'] = array_merge($heya_cam, $norm_cam);
            $items[$c][] = $d;
            $prev = $tatemono;
        }
        $this->_data['list'] = $items;

        $tenpos = array();
        $model_shop = new Renew_Model_BukkenTenpo();
        foreach ($data[0] as $d)
        {
            $rslt = $model_shop->getTenpoList($d['T03_DAIHYO_HEYA_CD']);
            foreach ($rslt as $r)
            {
                if ($r['T03_TENPO_CD'] == $d['T03_TENPO_CD'])
                { // 代表店舗だけ
                    $tenpos[$r['T03_TENPO_CD']] = $r;
                }
            }
        }
        // CALLNOTE
        foreach ($tenpos as $i => $tenpo)
        {
            $tempData = Apm_ShopUtil::getCallingData($tenpo, Apm_Config_Shop::FREE_CONNECTION_NO_1);
            $tenpos[$i]['IS_FREE_CALL'] = $tempData['IS_FREE_CALL'];
            if ($tempData['IS_FREE_CALL'])
            {
                $tenpos[$i]['FREE_CALLING'] = $tempData['TEL_01'];
                $tenpos[$i]['CONVERT_CONNECTION_NO'] = Apm_Bukkenitems::GetBukkenWebCallingNo($tenpo, Apm_Config_Rstdtl::CAMPAIGN_PC);
            }
        }
        $this->_data['tenpos'] = $tenpos;
    }

    /**
     * 入力チェック
     *
     * @param unknown $params リクエストパラメータ
     * @return number 0:OK,1:NG
     */
    private function checkParams($params)
    {
        $error = 0;

        // 姓・名の全角文字チェック
        $key = array();
        $key[] = 'kanji_sei';
        $key[] = 'kanji_mei';
        foreach ($key as $k)
        {
            if ($this->checkZenkaku($params[$k]))
            {
                $this->_data['name_error'] = 1;
                $this->_data[$k . '_error'] = "error";
                $error = 1;
            }
        }
        // セイ・メイの全角カナ文字チェック
        $key = array();
        $key[] = 'kana_sei';
        $key[] = 'kana_mei';
        foreach ($key as $k)
        {
            if ($this->checkZenkakuKana($params[$k]))
            {
                $this->_data['name_error'] = "error";
                $this->_data[$k . '_error'] = "error";
                $error = 1;
            }
        }
        // メールアドレス・電話番号チェック
        $params['mail'] = trim($params['mail']);
        $params['tel'] = trim($params['tel']);
        if (empty($params['mail']) && empty($params['tel']))
        {
            // メールアドレス・電話番号の両方が未入力の場合
            $this->_data['renraku_empty_error'] = "error";
            $this->_data['renraku_error'] = "error";
            $error = 1;
        }
        else
        {
            if (!empty($params['mail']) && $this->checkMail($params['mail']))
            {
                // メールアドレスが入力されているかつ、入力形式が正しくない場合
                $this->_data['mail_error'] = "error";
                $this->_data['renraku_error'] = "error";
                $error = 1;
            }
            if (!empty($params['tel']) && !preg_match("/^[0-9]+$/u", $params['tel']))
            {
                // 電話番号が入力されているかつ、入力形式が正しくない場合
                $this->_data['tel_error'] = "error";
                $this->_data['renraku_error'] = "error";
                $error = 1;
            }
        }
        // お問い合わせ内容チェック
        $checks = 0;
        for ($i = 1; $i <= 4; $i++)
        {
            // チェックボックス４つ分をループ
            if ($params['check' . $i] == 'on')
            {
                // チェックボックスonがあれば、+1
                $checks++;
            }
        }
        if ($checks == 0)
        {
            // チェックボックスがすべてoffの場合
            $this->_data['checks_error'] = "error";
            $error = 1;
        }
        if (strlen($params['shosai']) > 500)
        {
            // 自由記載欄の文字数が500文字以上の場合
            $this->_data['shosai_error'] = "error";
            $error = 1;
        }

        return $error;
    }

    /**
     * テンプレート用パラメータ作成(店舗情報)
     *
     * @param unknown $params リクエストパラメータ
     */
    private function makeTemplateParams1($params)
    {
        $tenpo = $this->_data['tenpos'];

        $shop = array();
        foreach ($params as $key => $val)
        {
            if (substr($key, 0, 6) == 'ShopCd')
            {
                $shop[$key] = array(
                    'code' => $val
                );
                foreach ($tenpo as $k1 => $v1)
                {
                    if ($v1['T03_TENPO_CD'] == $val)
                    {
                        $shop[$key]['name'] = $v1['T03_TENPO_NAME'];
                        $shop[$key]['heya'] = $v1['T03_HEYA_CD'];
                        break;
                    }
                }
            }
        }
        $this->_data['shop'] = $shop;
    }

    /**
     * SEO対策用のmetaタグに配置する文章を設定
     */
    protected function setSeoMeta()
    {
        $params = $this->getParameters();

        $subTitle = '';

        if ($params["Step"] == 1)
        {
            $subTitle = ' 情報の入力';
        }
        else if ($params["Step"] == 2)
        {
            $subTitle = ' 入力内容の確認';
        }

        $this->_meta_title = 'まとめてお問い合わせ' . $subTitle . '【アパマンショップ】';
    }

}
?>
